# -*- coding: utf-8 -*-
from compiler.ast import obj
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from companies.models import Company, Company_Area, Company_Industry
from countries_states.models import State, Municipal, Country
from companies.forms import get_company_areas, get_company_industries

from userprofiles import settings as up_settings
from userprofiles.utils import UserProfile

class ProfileForm(forms.ModelForm):
    first_name = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Ingrese su nombre')}),
        max_length=30,
        error_messages={'required': _(u"Ingrese su nombre")},
        label=_(u"Nombre")
    )

    last_name = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Ingrese sus apellidos')}),
        max_length=30,
        error_messages={'required': _(u"Ingrese sus apellidos")},
        label=_(u"Apellidos")
    )

    email = forms.EmailField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Correo electrónico')}),
        max_length=75,
        error_messages={'required': _(u"Ingrese su correo electrónico")},
        label="E-mail"
    )

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        if not up_settings.PROFILE_ALLOW_EMAIL_CHANGE:
            del self.fields['email']
        else:
            self.fields.keyOrder.remove('email')
            self.fields.keyOrder.insert(0, 'email')

        if not up_settings.REGISTRATION_FULLNAME:
            del self.fields['first_name']
            del self.fields['last_name']
        else:
            self.fields.keyOrder.remove('first_name')
            self.fields.keyOrder.remove('last_name')
            self.fields.keyOrder.insert(0, 'first_name')
            self.fields.keyOrder.insert(1, 'last_name')

    def update(self, *args, **kwargs):
        user = super(ProfileForm, self).save(*args, **kwargs)
        if up_settings.REGISTRATION_FULLNAME:
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
        if up_settings.PROFILE_ALLOW_EMAIL_CHANGE:
            user.email = self.data['email']
        if up_settings.REGISTRATION_FULLNAME or up_settings.PROFILE_ALLOW_EMAIL_CHANGE:
            user.save()

        if hasattr(self, 'save_profile'):
            self.save_profile(user, *args, **kwargs)

        return user

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']
